
package com.google.project.server;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.google.project.client.Service.ProjectStaffService;
import com.google.project.server.entity.Project;
import com.google.project.server.entity.ProjectStaff;
import com.google.project.server.entity.ProjectTask;
import com.google.project.server.entity.TaskRequire;
import com.google.project.server.entity.Users;
import com.google.project.shared.CommonFuntion;
import com.google.project.shared.ProjectDTO;
import com.google.project.shared.ProjectStaffDTO;
import com.google.project.shared.TaskRequireDTO;
import com.google.project.shared.UsersDTO;

@SuppressWarnings("serial")
public class ProjectStaffServiceImpl extends RemoteServiceServlet implements ProjectStaffService {

	@Override
	public ProjectStaffDTO addStaff(ProjectStaffDTO staffDTO) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		ProjectStaff staff = null;
		try {
			staff = new ProjectStaff(staffDTO);
			pm.makePersistent(staff);
		} finally {
			pm.close();
		}
		return staffDTO;
	}
	//truyen vao ProjectId, get all operator
	@Override
	public List<ProjectStaffDTO> getProjectStaffList(String projectId) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Project project = pm.getObjectById(Project.class, projectId);
		List<ProjectStaffDTO> staffList = new ArrayList<ProjectStaffDTO>();
		if(project.getListOfStaff() != null && project.getListOfStaff().size() > 0) {
			for(int i = 0; i < project.getListOfStaff().size(); i++ ) {
				staffList.add(project.getListOfStaff().get(i).toDTO());
			}
		}
		
		return staffList;
	}

	@Override
	public void deleteProjectStaff(String id) {
		// TODO Auto-generated method stub
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			ProjectStaff projectStaff = pm.getObjectById(ProjectStaff.class, id);
			if (projectStaff != null) {
				pm.deletePersistent(projectStaff);
			}
		} finally {
			pm.close();
		}
		
	}

	@Override
	public ProjectStaffDTO addStaff(UsersDTO userDTO,
			ProjectStaffDTO projectStaffDTO) {
		// TODO Auto-generated method stub
		PersistenceManager pm = PMF.get().getPersistenceManager();
		ProjectStaff staff = null;
		try {
			Project project = pm.getObjectById(Project.class, userDTO.getCurrentProjID());
			staff = new ProjectStaff(projectStaffDTO);
			project.getListOfStaff().add(staff);
			pm.makePersistent(project);
		} finally {
			pm.close();
		}
		return projectStaffDTO;
	}	
	//get current projectID by userID and statusProject



	@SuppressWarnings("unchecked")
	@Override
	public List<ProjectStaffDTO> getAllPrjStaff() {
		List<ProjectStaffDTO> listProjectStaff = new ArrayList<ProjectStaffDTO>();
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query q = pm.newQuery(ProjectStaff.class);
		try {
			List<ProjectStaff> list = (List<ProjectStaff>) q.execute();
			for (ProjectStaff projectStaff : list) {
				listProjectStaff.add(projectStaff.toDTO());
			}
		} catch (Exception e) {
			log(e.getMessage());
		} finally {
			pm.close();
		}
		return listProjectStaff;
	}
	
	
//	@SuppressWarnings("unchecked")
//	@Override
	public List<ProjectStaff> getStaffOfTask(String taskId) {
		List<ProjectStaffDTO> listProjectStaff = new ArrayList<ProjectStaffDTO>();
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query q = pm.newQuery(ProjectStaff.class,"taskId ==\""+taskId+"\"");
		List<ProjectStaff> list = null;
		try {
			
			list =(List<ProjectStaff>) q.execute();
			for (ProjectStaff projectStaff : list) {
				listProjectStaff.add(projectStaff.toDTO());
			}
		} catch (Exception e) {
			log(e.getMessage());
		} finally {
			pm.close();
		}
		return list;
	}
	
	
	
	@Override
	public ProjectStaffDTO addStaff(String projectId, ProjectStaffDTO projectStaffDTO) {
		// TODO Auto-generated method stub
		PersistenceManager pm = PMF.get().getPersistenceManager();
		ProjectStaff staff = null;
		try {
			Project project = pm.getObjectById(Project.class, projectId);
			staff = new ProjectStaff(projectStaffDTO);
			project.getListOfStaff().add(staff);
			pm.makePersistent(project);
		} finally {
			pm.close();
		}
		return projectStaffDTO;
	}

	@Override
	public void addStaffList(List<UsersDTO> userDTOList, ProjectDTO projectChoosed,TaskRequireDTO taskRequireDTO) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			for(UsersDTO userDTO : userDTOList) {
				if(userDTO.getUserGroup() == null) {
					userDTO.setUserGroup(0L);
				}
				ProjectStaffDTO projectStaffDTO  = new ProjectStaffDTO(userDTO.getUserId(),userDTO.getUserName(), userDTO.getFullName(),
						userDTO.getUserCode(),Integer.parseInt(userDTO.getUserGroup().toString()), projectChoosed.getStartDate(), projectChoosed.getDueDate(), 
						userDTO.getSpecializeID(), userDTO.getSpecializeName(), userDTO.getExperient(), 0, 
						projectChoosed.getProjectID(),taskRequireDTO.getTaskId());
				addStaff(projectChoosed.getProjectID(), projectStaffDTO);
			
			}
			
			//update numOfRep
			Project project=pm.getObjectById(Project.class,projectChoosed.getProjectID());
			ProjectDTO projectDTO = project.toDTO();
			projectDTO.setNumOfEmpRep(projectDTO.getNumOfEmpRep()+ userDTOList.size());
			//neu numOfRep<numOfReq+numOfOpt hoac numOfOPTRep<numofOPT thi doi trang thai IsReq=3
			if(projectDTO.getNumOfEmpRep()<(projectDTO.getNumOfEmpReq()+projectDTO.getNumOfOPT()) || projectDTO.getNumOfOPTRep()<projectDTO.getNumOfOPT()){
				projectDTO.setIsReq(3);
			}
			//neu numOfRep>=numOfReq va numOfOPTRep>=numofOPT thi doi trang thai IsReq=4
			if(projectDTO.getNumOfEmpRep()>=(projectDTO.getNumOfEmpReq()+projectDTO.getNumOfOPT()) && projectDTO.getNumOfOPTRep()>=projectDTO.getNumOfOPT()){
				projectDTO.setIsReq(4);
			}
			
			//update numOfReponse in taskRequire
			if(taskRequireDTO.getSpecializeId()!=null){
				TaskRequire taskReq=pm.getObjectById(TaskRequire.class, taskRequireDTO.getId());
				
				taskRequireDTO.setNumOfResponse(taskReq.toDTO().getNumOfResponse()+userDTOList.size());
				taskReq.updateFromDTO(taskRequireDTO);
			}else{//update NumOfIOPT dap ung
				System.out.println(projectDTO.getNumOfOPTRep()+"/"+userDTOList.size());
				projectDTO.setNumOfOPTRep(projectDTO.getNumOfOPTRep()+userDTOList.size());
			}
			project.updateFromDTO(projectDTO);
		} finally {
			pm.close();
		}
	}	
	@Override
	public void updateProjectStaff(List<ProjectStaffDTO> projectStaffDTOList, List<UsersDTO> usersDTOList, int regisOrRemoveFlag) {
		UsersServiceImpl userImpl = new UsersServiceImpl();
		PersistenceManager pm = PMF.get().getPersistenceManager();
		ProjectStaff staff = null;
		try {
			for(int i = 0 ; i < projectStaffDTOList.size(); i++) {
				if(regisOrRemoveFlag == 0) {
					projectStaffDTOList.get(i).setStatus(1);	//Xac nhan nhan vien nay dang tham gia vao du an
					staff = pm.getObjectById(ProjectStaff.class, projectStaffDTOList.get(i).getId());
					staff.updateFromDTO(projectStaffDTOList.get(i));
					String staffId  = staff.getUserId();
					String projectId = staff.getProjectId();
					for(UsersDTO user : usersDTOList) {
						if(user.getUserId().equals(staffId)) {
							user.setCurrentProjID(projectId);
							userImpl.updateUser(user);
						}
					}
				} else if(regisOrRemoveFlag == 1) {
					
					//can change 
					Query q = pm.newQuery(ProjectTask.class);
					List<ProjectTask> listTask = (List<ProjectTask>) q.execute();
					if(listTask!=null&&listTask.size()>0)
					{
						for(ProjectTask task:listTask)
						{
							if(task.getOptUserId().equals(projectStaffDTOList.get(i).getUserId()))
							{
								task.setOptAccountName("");
								task.setOptUserId("0");
							}
						}
					}
					//----can change
				
					if(projectStaffDTOList.get(i).getStatus() == 0) {	//Doi voi nhung nhan vien chua thuc su tham gia vao du an thi khi 
						ProjectStaff pjStaff = pm.getObjectById(ProjectStaff.class, projectStaffDTOList.get(i).getId());
						pm.deletePersistent(pjStaff);
					} else {
						projectStaffDTOList.get(i).setStatus(2);
						projectStaffDTOList.get(i).setFinishtDate(CommonFuntion.removeTime(new Date()));
						//Rut nhan vien nay da hoan thanh va rut khoi du an
						staff = pm.getObjectById(ProjectStaff.class, projectStaffDTOList.get(i).getId());
						staff.updateFromDTO(projectStaffDTOList.get(i));
						String staffId  = staff.getUserId();
						for(UsersDTO user : usersDTOList) {
							if(user.getUserId().equals(staffId)) {
								user.setCurrentProjID("");
								userImpl.updateUser(user);
							}
						}
					}
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pm.close();
		}
	}
	
	
	void updateForCloseProject(List<ProjectStaff> data)
	{
		PersistenceManager pm = PMF.get().getPersistenceManager();
		PersistenceManager pm1 = PMF.get().getPersistenceManager();
	
	
		for(ProjectStaff staff : data)
		{
			//neu chua ra duoc rut khoi du an
			if(staff.getStatus()!=2)
			{
				//cap nhap lai prroject hien tai cua user
				Users user = pm.getObjectById(Users.class,staff.getUserId());
				user.setCurrentProjID("");
				
				if(staff.getStatus()==0)
				{
					ProjectStaff newStaff = pm1.getObjectById(ProjectStaff.class,staff.getId());
					//neu chua tham gia du an xoa thong tin
					pm1.deletePersistent(newStaff);
				}
				else
				{
					//neu dang tham gia du an cap nhap lai ngay kett thuc , chuyen trang thai
					staff.setFinishDate(CommonFuntion.removeTime(new Date()));
					staff.setStatus(2);
				}
			}
			
		}
		
		pm.close();
		pm1.close();
		
	}
	
	

	
	@Override
	public List<ProjectStaffDTO> searchPJWithTime(Long fromDate, Long toDate) {
		List<ProjectStaffDTO> all = getAllPrjStaff();
		List<ProjectStaffDTO> projectStaffDTOList = new ArrayList<ProjectStaffDTO>();
		for(ProjectStaffDTO staff : all) {
			if((((staff.getStartDate() <= fromDate) && (staff.getFinishtDate() >= fromDate)) 
			   || (staff.getStartDate() <= toDate) && (staff.getFinishtDate() >= toDate))&&staff.getStatus()!=2) {
				projectStaffDTOList.add(staff);
			}
		}
		return projectStaffDTOList;
	}	
}
